package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/olivere/elastic/v7"
	"log"
	"os"
	"time"
)

type EsService struct {
}
type User struct {
	FirstName string `json:"firstname"`
	Address   string `json:"address"`
}

func (s *EsService) CreateClient() (client *elastic.Client, err error) {
	host := "http://192.168.31.226:9200"
	newClient, err := elastic.NewClient(
		elastic.SetURL(host),
		elastic.SetSniff(false),
		elastic.SetGzip(true),
		elastic.SetHealthcheck(true),
		elastic.SetHealthcheckTimeout(10*time.Second),
		elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC", log.LstdFlags)), // 设置日志输出的名字
		elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags)),         // 输出日志级别
	)
	if err != nil {
		err = errors.New("连接es失败")
	}
	return newClient, nil
}
func main() {
	es := EsService{}
	client, err := es.CreateClient()
	if err != nil {
		fmt.Println(err)
	}

	exists, err := client.IndexExists("user").Do(context.Background())
	if err != nil {
		fmt.Println("index不存在")
	}
	fmt.Println(exists, "exists")

	query := elastic.NewMatchQuery("address", "Street")

	do, err := client.Search().Index("user").Query(query).Do(context.Background())
	if err != nil {
		return
	}
	user := User{}
	for _, v := range do.Hits.Hits {
		data, _ := v.Source.MarshalJSON()
		json.Unmarshal(data, &user)
	}

}
